package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.SQLPageDoing;
import com.rockcent.mall.lib.dto.UserMallDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by DK on 17/3/29.
 */
@Repository
public class UserMallRepositoryImpl implements UserMallRepositoryCustom {
    private static final Logger log = LoggerFactory.getLogger(UserMallRepositoryImpl.class);

    @Autowired
    NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public PageResult<UserMallDto> findMallChildAccountResourcePage(Long titleId, Long mallId, PageResult page) {
        SQLPageDoing<UserMallDto> doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("select %s from user_mall um left join mall m on um.mall_id = m.id where 1=1 ");

            if (titleId != null) {
                sql.append(" and um.title_id = :titleId");
                params.put("titleId", titleId);
            }

            sql.append(" and um.mall_id = :mallId");
            params.put("mallId", mallId);
            sql.append(" order by um.date_created desc");
            fields.append("um.*, m.name mallName");
        };
        return doing.go(page, UserMallDto.class, objectMapper, jdbcTemplate, log);
    }
}
